package com.xyc.gulimall.product.web;

import com.xyc.gulimall.product.entity.CategoryEntity;
import com.xyc.gulimall.product.service.CategoryService;
import com.xyc.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {

        // TODO 1、查出所有的1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevelCategorys();

        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        double start = System.currentTimeMillis();
        Map<String, List<Catalog2Vo>> catalogJson = categoryService.getCatalogJson();
        double end = System.currentTimeMillis();
        System.out.println(end - start / 1000);
        return catalogJson;
    }

    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        //1、获取一把锁，只要锁名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");

        //2、加锁
//        lock.lock();    //阻塞等待
        //redisson的看门狗机制：
        //1）、锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s。无需担心业务过长，锁自动过期被删掉。
        //2）、加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认在30s以后自动删除。-防止死锁

        lock.lock(10, TimeUnit.SECONDS); //10s自动解锁，注意自动解锁时间一定要大于业务处理时间。因为不会自动续期
        try {
            System.out.println("加锁成功，执行业务..." + Thread.currentThread().getId());
            Thread.sleep(30000);

        } catch (Exception e) {

        } finally {
            //3、释放锁
            System.out.println("释放锁..." + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    /**
     * 分布式闭锁
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();   //等待闭锁完成

        return "所有班级学生都走了，可以锁门了！";
    }

    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Integer id) {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();   //计数减一

        return id + "班都走了";
    }

    /**
     * 信号量
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
//        park.acquire(); //获取一个信号，占一个车位，阻塞
        boolean b = park.tryAcquire();//非阻塞，有返回true，无返回false（限流）
        if (b) {
            //执行业务
        } else {
            return "当前没有车位，请稍后再试...";
        }

        return "ok";
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release(); //释放一个车位

        return "ok";
    }

}
